package cn.stylefeng.guns.modular.rest.storagePut;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionmaterialParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionmaterialResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionmaterialService;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.model.result.OrderPutResult;
import cn.stylefeng.guns.modular.order.service.OrderPutService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.storage.entity.StoragePutSingle;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.model.params.StoragePutExceptionParam;
import cn.stylefeng.guns.modular.storage.model.params.StoragePutParam;
import cn.stylefeng.guns.modular.storage.model.params.StoragePutSingleParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StoragePutResult;
import cn.stylefeng.guns.modular.storage.model.result.StoragePutSingleResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StoragePutExceptionService;
import cn.stylefeng.guns.modular.storage.service.StoragePutService;
import cn.stylefeng.guns.modular.storage.service.StoragePutSingleService;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 入库
 */
@Controller
@RequestMapping("/rest/storagePut")
public class restStoragePutController2 extends BaseController  {

    @Autowired
    private UserAop userAop;

    @Autowired
    private StoragePutService storagePutService;

    @Autowired
    private StoragePutSingleService storagePutSingleService;

    @Autowired
    private StorageOutDetailedService storageOutDetailedService;
    
    @Autowired
    private BasicPositionService basicPositionService;
    
    private Lock lock = new ReentrantLock();

    @Autowired
    private BasicGoodsService basicGoodsService;

    @Autowired
    private StorageStockService storageStockService;

    @Autowired
    private StoragePutExceptionService storagePutExceptionService;

    /**
     * 入库
     * 查询入库单
     */
    @ResponseBody
    @RequestMapping("/storagelist")
    public ResponseData storagelist(StoragePutParam storagePutParam) {
		User user = userAop.getUser();
        storageOutDetailedService.unlockTheItemNew(user);
    	storagePutParam.setDeliverId(user.getDeliverId());
    	Long deptId = user.getDeptId();
    	List<StoragePutResult> list = this.storagePutService.findPageBySpecStorageListNew(storagePutParam,deptId,user.getOperateId());
		StoragePutSingleParam storagePutSingleParam = new StoragePutSingleParam();
    	storagePutSingleParam.setSingleState("appstorage");
    	for (StoragePutResult r : list) {
    		storagePutSingleParam.setStorageNumber(r.getStorageNumber());
        	List<StoragePutSingleResult> list2 = this.storagePutSingleService.findPageDISTINCTGoodsNew(storagePutSingleParam);
//        	for (StoragePutSingleResult r2 : list2) {
//            	QueryWrapper<StoragePutSingle> queryWrapper = new QueryWrapper<StoragePutSingle>();//查询是否有未入
//            	queryWrapper.eq("single_state", "NOT_RECEIVED");
//            	queryWrapper.eq("goods_id", r2.getGoodsId());
//            	queryWrapper.eq("storage_number", r2.getStorageNumber());
//        		int count = storagePutSingleService.count(queryWrapper);
//        		if(count > 0) {
//        			r2.setSingleState("NOT_RECEIVED");
//        		} else {
//        			r2.setSingleState("PENDING_APPROVAL");
//        		}
//    		}
			if(ToolUtil.isNotEmpty(list2)){
				r.setGoodsNum(String.valueOf(list2.size()));
			}
        	r.setList(list2);
		}
        return ResponseData.success(list);
    }
    
    /**
     * 入库
     *查询批次列表
     */
    @ResponseBody
    @RequestMapping("/applistbatchwork")
    public ResponseData applistbatchwork(StoragePutSingleParam storagePutSingleParam) {
		User user = userAop.getUser();
		//推荐库位
        try {
            storagePutSingleService.allotPositionNew(storagePutSingleParam,user);
            StoragePutSingleParam sParam = new StoragePutSingleParam();
            sParam.setGoodsId(storagePutSingleParam.getGoodsId());
            sParam.setStorageNumber(storagePutSingleParam.getStorageNumber());
            sParam.setSingleState("NOT_RECEIVED");
            List<StoragePutSingleResult> list =  storagePutSingleService.findListBySpec(sParam);
    		storageStockService.batchAddNewNew(list,user);//新增库存
        } catch (Exception e) {
        }
        
        storagePutSingleParam.setSingleState("appstorage");
        List<StoragePutSingleResult> list = this.storagePutSingleService.findPageDISTINCTbatchNew(storagePutSingleParam);
        for (StoragePutSingleResult r : list) {
        	StoragePutSingleParam p = new StoragePutSingleParam();
        	p.setStorageNumber(r.getStorageNumber());
        	p.setGoodsId(r.getGoodsId());
        	p.setSingleBatchnumber(r.getSingleBatchnumber());
            p.setSingleState("NOT_RECEIVED");
        	List<tarpanBatch> list2 = this.storagePutSingleService.TcustomListNew(p);
        	r.setList(list2);
		}
        return ResponseData.success(list);
    }

    /**
     * 入库
     * 新增批次
     */
    @RequestMapping("/appaddItem")
    @ResponseBody
    public ResponseData appaddItem(StoragePutSingleParam storagePutSingleParam) {
    	User user = userAop.getUser();
        Long goodsId = storagePutSingleParam.getGoodsId();
        BasicGoods basicGoods = basicGoodsService.getById(goodsId);

        BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());//体积

        BigDecimal putNum = new BigDecimal(storagePutSingleParam.getPutNum());//数量
        BigDecimal u = new BigDecimal(basicGoods.getGoodsCharging());//单价

        BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量

        if(ToolUtil.isEmpty(storagePutSingleParam.getSingleDateofmanufacture())) {
        	storagePutSingleParam.setSingleDateofmanufacture(DateUtil.getDate());//生产日期
        }
        if(ToolUtil.isEmpty(storagePutSingleParam.getSingleBatchnumber())) {
        	storagePutSingleParam.setSingleBatchnumber(storagePutSingleParam.getSingleDateofmanufacture().replaceAll("-", ""));
        }
        storagePutSingleParam.setSingleRebubbles( basicGoods.getGoodsHeavybubble());//singleRebubbles  重泡货
        storagePutSingleParam.setSinglePacking(basicGoods.getGoodsPacking());//singlePacking  商品包装
        storagePutSingleParam.setSingleLargeclass(basicGoods.getGoodsBigtype());//singleLargeclass 商品大类
        storagePutSingleParam.setSingleGoodstype(basicGoods.getGoodsType());//singleGoodstype 商品类别
        storagePutSingleParam.setSinglePutcondition(basicGoods.getGoodsCondition());//singlePutcondition 保管条件
        storagePutSingleParam.setGoodsname(basicGoods.getGoodsName());//商品名称
        storagePutSingleParam.setGoodsNumber( basicGoods.getGoodsNumber());//商品编号
        storagePutSingleParam.setDetailedPutvolume((putNum.multiply(v)).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入体积
        storagePutSingleParam.setGoodsVolume(v.toString());
        storagePutSingleParam.setPutWeight((putNum.multiply(w)).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入重量
        storagePutSingleParam.setGoodsWeight(w.toString());
        storagePutSingleParam.setPutBalenum(storagePutSingleParam.getPutNum());//入大包数
        storagePutSingleParam.setSingleMoney((putNum.multiply(u)).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应入金额
        storagePutSingleParam.setUnitprice(basicGoods.getGoodsCharging());//单价
        storagePutSingleParam.setSinglePiecenum("1");
        
		lock.lock();//获取锁
		try {
	        this.storagePutSingleService.increaseNew(storagePutSingleParam,user);

			//推荐库位
	        try {
	            storagePutSingleService.allotPositionNew(storagePutSingleParam,user);
	        } catch (Exception e) {
	        }
	        
            StoragePutSingleParam sParam = new StoragePutSingleParam();
            sParam.setGoodsId(storagePutSingleParam.getGoodsId());
            sParam.setStorageNumber(storagePutSingleParam.getStorageNumber());
            sParam.setSingleState("NOT_RECEIVED");
            List<StoragePutSingleResult> list =  storagePutSingleService.findListBySpec(sParam);
    		storageStockService.batchAddNewNew(list,user);//新增库存
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return ResponseData.success();
    }

    /**
     * 入库
     * 入库撤销
     */
    @RequestMapping("/apprevokewoke")
    @ResponseBody
    public ResponseData apprevokewoke(StoragePutSingleParam storagePutSingleParam) {
        StoragePutSingle storagePutSingle = storagePutSingleService.getById(storagePutSingleParam.getId());
        storagePutSingle.setSingleState("NOT_RECEIVED");
        storagePutSingle.setRealNum("");
        storagePutSingle.setPositionNumber("");
        ToolUtil.copyProperties(storagePutSingle,storagePutSingleParam);
        this.storagePutSingleService.update(storagePutSingleParam);


		StorageStockParam storageStockParam = new StorageStockParam();
		storageStockParam.setPositionNumber("");
		storageStockParam.setPositionId(0l);
		storageStockParam.setAreaId(0l);
		storageStockParam.setAreaNumber("");

		storageStockParam.setId(Integer.valueOf(storagePutSingle.getStockId()+""));
		this.storageStockService.update(storageStockParam);
        return ResponseData.success();
    }
    
    /**
     * 入库
     * 数量有误、托盘入库
     */
    @RequestMapping("/appstoragewoke")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData appstoragewoke(StoragePutSingleParam storagePutSingleParam,String exceptionnodes,String exceptiontype){
		User user = userAop.getUser();
        StoragePutSingle storagePutSingle = storagePutSingleService.getById(storagePutSingleParam.getId());
        if(ToolUtil.isNotEmpty(storagePutSingleParam.getRealNum())) {
    		//异常处理
    		BigDecimal num = new BigDecimal(storagePutSingle.getPutNum());
    		BigDecimal realNum = new BigDecimal(storagePutSingleParam.getRealNum());
    		if(num.compareTo(realNum) != 0) {
    			StoragePutExceptionParam storagePutExceptionParam = new StoragePutExceptionParam();
    			storagePutExceptionParam.setPutNumber(storagePutSingle.getStorageNumber());
    			storagePutExceptionParam.setDetailedId(Long.parseLong(storagePutSingle.getId().toString()));
    			storagePutExceptionParam.setTypes(exceptiontype);
    			storagePutExceptionParam.setNum(num.toString());
    			storagePutExceptionParam.setShirunum(realNum.toString());
    			storagePutExceptionParam.setNotes(exceptionnodes);
    			storagePutExceptionParam.setUserName(user.getName());
    			storagePutExceptionParam.setChuliTime(DateUtil.getDateS());
    			storagePutExceptionService.add(storagePutExceptionParam);
    		}
        }
        
		StorageStockParam ssP = new StorageStockParam();//库存输入类
        StorageStock ssr = storageStockService.getById(storagePutSingle.getStockId());
		
		BasicCustomer basicCustomer = basicCustomerService.getById(ssr.getCustomerId());
		if(ToolUtil.isNotEmpty(basicCustomer.getBinding()) && basicCustomer.getBinding().equals("Yes")) {
			BasicPositionmaterialParam positionmaterialParam = new BasicPositionmaterialParam();
			positionmaterialParam.setDeptId(user.getDeptId());
			positionmaterialParam.setMaterialNumber(storagePutSingle.getGoodsNumber());
			BasicPositionmaterialResult basicPositionmaterialResult = basicPositionmaterialService.findBySpec(positionmaterialParam,user.getOperateId());
			if(basicPositionmaterialResult != null) {
				if(!basicPositionmaterialResult.getPositionNumber().equals(storagePutSingleParam.getPositionNumber())) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					return ResponseData.error("Storage location does not match commodity; unable to inbound！");
				}
			}
		}
        
		//校验库位
		BasicPositionParam basicPositionParam = new BasicPositionParam();
		basicPositionParam.setPositionNumber(storagePutSingleParam.getPositionNumber());
		basicPositionParam.setWarehouseId(Integer.parseInt(ssr.getWarehouseId().toString()));
		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam,user.getDeptId(),user.getOperateId());
		if(basicPositionResult == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
			return ResponseData.error("Storage location does not exist！");
		}

		//是否储位限品
		if(ToolUtil.isNotEmpty(basicCustomer.getStorageLimitFlag()) && basicCustomer.getStorageLimitFlag().equals("Yes")) {
			ResponseData responseData = storageLimitItems(user, storagePutSingleParam.getPositionNumber(), ssr.getWarehouseId(),storagePutSingle.getGoodsNo(),storagePutSingle.getGoodsNumber(),storagePutSingle.getSingleBatchnumber());
			if(responseData.getCode() == 500) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				return responseData;
			}
		}


		//更新入库明细
        StoragePutSingleParam ssparam =new StoragePutSingleParam();
		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
        if(ToolUtil.isNotEmpty(storagePutSingle.getPositionNumber())) {
            if(!storagePutSingle.getPositionNumber().equals(storagePutSingleParam.getPositionNumber())) {
        		//修改 未入  库存
    			bpp.setPositionNumber(storagePutSingleParam.getPositionNumber());
    			bpp.setWarehouseId(Integer.parseInt(ssr.getWarehouseId().toString()));
    			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,null,null);//库位信息
                ssr.setPositionId(Long.parseLong(bpr.getId().toString()));
                ssr.setPositionNumber(storagePutSingleParam.getPositionNumber());
                ssr.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
                ssr.setAreaNumber(bpr.getAreaNumber());//库区编号
                ToolUtil.copyProperties(ssr,ssP);
                storageStockService.update(ssP);
            	
            	storagePutSingle.setPositionNumber(storagePutSingleParam.getPositionNumber());
            }
        } else {
    		//修改 未入  库存
			bpp.setPositionNumber(storagePutSingleParam.getPositionNumber());
			bpp.setWarehouseId(Integer.parseInt(ssr.getWarehouseId().toString()));
			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,null,null);//库位信息
            ssr.setPositionId(Long.parseLong(bpr.getId().toString()));
            ssr.setPositionNumber(storagePutSingleParam.getPositionNumber());
            ssr.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
            ssr.setAreaNumber(bpr.getAreaNumber());//库区编号
            ToolUtil.copyProperties(ssr,ssP);
            storageStockService.update(ssP);
        	
        	storagePutSingle.setPositionNumber(storagePutSingleParam.getPositionNumber());
        }
        if(storagePutSingleParam.getRealNum()==null){
            storagePutSingle.setRealNum(storagePutSingle.getPutNum());
        }else{
            storagePutSingle.setRealNum(ssparam.getRealNum());
        }
        storagePutSingle.setSingleState("PENDING_APPROVAL");
        storagePutSingle.setPutName(user.getName());
        ToolUtil.copyProperties(storagePutSingle,storagePutSingleParam);
        this.storagePutSingleService.update(storagePutSingleParam);
        return ResponseData.success();
    }

    @Autowired
    private BasicPositionmaterialService basicPositionmaterialService;

    @Autowired
    private BasicCustomerService basicCustomerService;
    
    /**
     * 入库
     * 批次入库
     * goodsId storageNumber singleBatchnumber
     */
    @RequestMapping("/appstoragebatch")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData appstoragebatch(StoragePutSingleParam storagePutSingleParam) {
		StoragePutSingle storagePutSingle = storagePutSingleService.getById(storagePutSingleParam.getId());
    	String singleBatchnumber = storagePutSingleParam.getSingleBatchnumber();
    	//解决参数中的 英文括号
    	if (singleBatchnumber!=null&&singleBatchnumber!="") {
    		singleBatchnumber = singleBatchnumber.replace("& #40;", "(");
    		singleBatchnumber = singleBatchnumber.replace("& #41;", ")");
    		storagePutSingleParam.setSingleBatchnumber(singleBatchnumber);
    	}
		User user = userAop.getUser();
    	storagePutSingleParam.setSingleState("NOT_RECEIVED");
    	List<StoragePutSingleResult> rlist = storagePutSingleService.findListBySpec(storagePutSingleParam);
		BasicPositionParam basicPositionParam = new BasicPositionParam();
		StorageStockParam ssP = new StorageStockParam();//库存输入类
    	if(rlist.size()>0) {
            StorageStock ssr = storageStockService.getById(rlist.get(0).getStockId());
    		basicPositionParam.setWarehouseId(Integer.parseInt(ssr.getWarehouseId().toString()));
    		
    		BasicCustomer basicCustomer = basicCustomerService.getById(ssr.getCustomerId());
    		if(ToolUtil.isNotEmpty(basicCustomer.getBinding()) && basicCustomer.getBinding().equals("Yes")) {
    			BasicPositionmaterialParam positionmaterialParam = new BasicPositionmaterialParam();
    			positionmaterialParam.setDeptId(user.getDeptId());
    			positionmaterialParam.setMaterialNumber(rlist.get(0).getGoodsNumber());
    			BasicPositionmaterialResult basicPositionmaterialResult = basicPositionmaterialService.findBySpec(positionmaterialParam,user.getOperateId());
    			if(basicPositionmaterialResult != null) {
    				if(!basicPositionmaterialResult.getPositionNumber().equals(storagePutSingleParam.getPositionNumber())) {
    					return ResponseData.error("Storage location does not match commodity; unable to inbound！");
    				}
    			}
    		}
    	}
		//校验库位
		basicPositionParam.setPositionNumber(storagePutSingleParam.getPositionNumber());
		basicPositionParam.setDeliverId(user.getDeliverId());
		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam,user.getDeptId(),user.getOperateId());
		if(basicPositionResult == null) {
			return ResponseData.error("Storage location does not exist！");
		}

		if(rlist.size()>0) {
			StorageStock ssr = storageStockService.getById(rlist.get(0).getStockId());
			basicPositionParam.setWarehouseId(Integer.parseInt(ssr.getWarehouseId().toString()));

			BasicCustomer basicCustomer = basicCustomerService.getById(ssr.getCustomerId());
			//是否储位限品
			if(ToolUtil.isNotEmpty(basicCustomer.getStorageLimitFlag()) && basicCustomer.getStorageLimitFlag().equals("Yes")) {
				for (StoragePutSingleResult storagePutSingleResult : rlist) {
					ResponseData responseData = storageLimitItems(user, storagePutSingleParam.getPositionNumber(), ssr.getWarehouseId(),storagePutSingleResult.getGoodsNo(),storagePutSingleResult.getGoodsNumber(),storagePutSingleResult.getSingleBatchnumber());
					if(responseData.getCode() == 500) {
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
						return responseData;
					}
				}
			}
		}


    	StoragePutSingleParam sp = new StoragePutSingleParam();
		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
    	for (StoragePutSingleResult sr : rlist) {
            if(ToolUtil.isNotEmpty(sr.getPositionNumber())) {
                if(!sr.getPositionNumber().equals(storagePutSingleParam.getPositionNumber())) {
            		//修改 未入  库存
                    StorageStock ssr = storageStockService.getById(sr.getStockId());
        			bpp.setPositionNumber(storagePutSingleParam.getPositionNumber());
        			bpp.setDeliverId(user.getDeliverId());
        			bpp.setWarehouseId(Integer.parseInt(ssr.getWarehouseId().toString()));
        			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,user.getDeptId(),user.getOperateId());//库位信息
                    ssr.setPositionId(Long.parseLong(bpr.getId().toString()));
                    ssr.setPositionNumber(storagePutSingleParam.getPositionNumber());
                    ssr.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
                    ssr.setAreaNumber(bpr.getAreaNumber());//库区编号
                    ToolUtil.copyProperties(ssr,ssP);
                    storageStockService.update(ssP);
                	
                    sp.setPositionNumber(storagePutSingleParam.getPositionNumber());
                }
            } else {
        		//修改 未入  库存
                StorageStock ssr = storageStockService.getById(sr.getStockId());
    			bpp.setPositionNumber(storagePutSingleParam.getPositionNumber());
    			bpp.setDeliverId(user.getDeliverId());
    			bpp.setWarehouseId(Integer.parseInt(ssr.getWarehouseId().toString()));
    			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,user.getDeptId(),user.getOperateId());//库位信息
                ssr.setPositionId(Long.parseLong(bpr.getId().toString()));
                ssr.setPositionNumber(storagePutSingleParam.getPositionNumber());
                ssr.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
                ssr.setAreaNumber(bpr.getAreaNumber());//库区编号
                ToolUtil.copyProperties(ssr,ssP);
                storageStockService.update(ssP);
            	
                sp.setPositionNumber(storagePutSingleParam.getPositionNumber());
            }
    		sp.setSingleState("PENDING_APPROVAL");
    		sp.setId(sr.getId());
    		sp.setRealNum(sr.getPutNum());
			sp.setSingleDateofmanufacture(storagePutSingleParam.getSingleDateofmanufacture());
    		sp.setPutName(user.getName());
    		storagePutSingleService.update(sp);
    		sp = new StoragePutSingleParam();
    		ssP = new StorageStockParam();
		}
        return ResponseData.success();
    }
    
    @Autowired
    private OrderPutService orderPutService;
    
    /**
     * 入库
     *  批次撤销
     */
    @RequestMapping("/apprevokebatch")
    @ResponseBody
    public ResponseData apprevokebatch(StoragePutSingleParam storagePutSingleParam) {
    	String singleBatchnumber = storagePutSingleParam.getSingleBatchnumber();
    	//解决参数中的 英文括号
    	if (singleBatchnumber!=null&&singleBatchnumber!="") {
    		singleBatchnumber = singleBatchnumber.replace("& #40;", "(");
    		singleBatchnumber = singleBatchnumber.replace("& #41;", ")");
    		storagePutSingleParam.setSingleBatchnumber(singleBatchnumber);
    	}
    	storagePutSingleParam.setSingleState("PENDING_APPROVAL");
    	List<StoragePutSingleResult> rlist = storagePutSingleService.findListBySpec(storagePutSingleParam);
    	List<StoragePutSingle> list = new ArrayList<StoragePutSingle>();
    	StoragePutSingle sp = new StoragePutSingle();
    	for (StoragePutSingleResult sr : rlist) {
    		sp.setSingleState("NOT_RECEIVED");
            sp.setRealNum("");
            sp.setPositionNumber("");
    		sp.setId(sr.getId());
    		list.add(sp);
    		sp = new StoragePutSingle();
		}
    	if (list.size()>0) {
    		storagePutSingleService.updateBatchListState(list);
		}
        return ResponseData.success();
    }

    /**
     * 入库复核
     *  查询入库单列表
     */
    @ResponseBody
    @RequestMapping("/confirmsplist")
    public ResponseData confirmsplist(StoragePutParam storagePutParam,String condition) {
		User user = userAop.getUser();
        storageOutDetailedService.unlockTheItemNew(user);
    	storagePutParam.setDeliverId(user.getDeliverId());
    	Long deptId = user.getDeptId();
    	List<StoragePutResult> list = this.storagePutService.findPageBySpecStorageListNew(storagePutParam,deptId,user.getOperateId());
		StoragePutSingleParam storagePutSingleParam = new StoragePutSingleParam();
    	storagePutSingleParam.setSingleState("appstorageshenhe");
    	for (StoragePutResult r : list) {
    		storagePutSingleParam.setStorageNumber(r.getStorageNumber());
        	List<StoragePutSingleResult> list2 = this.storagePutSingleService.findPageDISTINCTGoodsNew(storagePutSingleParam);
        	List<StoragePutSingleResult> list3 = new ArrayList<StoragePutSingleResult>();
        	for (StoragePutSingleResult r2 : list2) {
            	QueryWrapper<StoragePutSingle> queryWrapper = new QueryWrapper<StoragePutSingle>();//查询是否有未入
            	queryWrapper.eq("single_state", "NOT_RECEIVED");
            	queryWrapper.eq("goods_id", r2.getGoodsId());
            	queryWrapper.eq("storage_number", r2.getStorageNumber());
        		int count = storagePutSingleService.count(queryWrapper);
        		if(count == 0) {
        			list3.add(r2);
        		} 
    		}
        	r.setList(list3);
		}
        return ResponseData.success(list);
    }

    /**
     * 入库复核
     * 查询库位列表
     */
    @ResponseBody
    @RequestMapping("/confirmplist")
    public ResponseData confirmplist(StoragePutSingleParam storagePutSingleParam) {
    	List<StoragePutSingleResult> list = this.storagePutSingleService.findpositionlist(storagePutSingleParam);
    	for (StoragePutSingleResult r : list) {
    		StoragePutSingleParam p = new StoragePutSingleParam();
    		p.setPositionNumber(r.getPositionNumber());
    		p.setStorageNumber(r.getStorageNumber());
    		p.setGoodsId(storagePutSingleParam.getGoodsId());
        	List<tarpanBatch> list2 = this.storagePutSingleService.confirmpositionGoodslistNew(p);
        	for (tarpanBatch r2 : list2) {
        		StoragePutSingleParam p2 = new StoragePutSingleParam();
        		p2.setPositionNumber(r2.getPositionNumber());
        		p2.setStorageNumber(r.getStorageNumber());
        		p2.setGoodsId(r2.getGoodsId());
        		p2.setSingleBatchnumber(r2.getSingleBatchnumber());
            	List<StoragePutSingleResult> list3 = this.storagePutSingleService.findListBySpecNew(p2);
            	r2.setList(list3);
			}
        	r.setList(list2);
		}
        return ResponseData.success(list);
    }
    
    /**
     * 复核
     * 更正实入数量
     */
    @RequestMapping("/editnum")
    @ResponseBody
    public ResponseData editnum(StoragePutSingleParam storagePutSingleParam){
		User user = userAop.getUser();
        StoragePutSingle storagePutSingle = storagePutSingleService.getById(storagePutSingleParam.getId());
		StoragePutParam spp = new StoragePutParam();
		spp.setStorageNumber(storagePutSingle.getStorageNumber());
		StoragePutResult sprt = storagePutService.findBySpec(spp);
		if(!sprt.getBillstate().equals("COMPLETED")) {
			return ResponseData.error("Document Status Changed！");
		}
    	try {
    		//异常处理
    		BigDecimal num = new BigDecimal(storagePutSingle.getPutNum());
    		BigDecimal realNum = new BigDecimal(storagePutSingleParam.getRealNum());
			StoragePutExceptionParam storagePutExceptionParam = new StoragePutExceptionParam();
			storagePutExceptionParam.setPutNumber(storagePutSingle.getStorageNumber());
			storagePutExceptionParam.setDetailedId(Long.parseLong(storagePutSingle.getId().toString()));
			storagePutExceptionParam.setTypes("Review Exception");
			storagePutExceptionParam.setNum(num.toString());
			storagePutExceptionParam.setShirunum(realNum.toString());
			storagePutExceptionParam.setUserName(user.getName());
			storagePutExceptionParam.setChuliTime(DateUtil.getDateS());
			storagePutExceptionService.add(storagePutExceptionParam);

			storagePutSingle.setRealNum("");
	        storagePutSingle.setSingleState("NOT_RECEIVED");
	        storagePutSingle.setPositionNumber("");
	        ToolUtil.copyProperties(storagePutSingle,storagePutSingleParam);
	        this.storagePutSingleService.update(storagePutSingleParam);
    	} catch (Exception e) {
    		return ResponseData.error("Exception occurred in backend during exception handling！");
    	}
        return ResponseData.success();
    }
    
    /**
     * 查询
     * 异常记录
     */
    @RequestMapping("/findyichang")
    @ResponseBody
    public ResponseData findyichang(StoragePutExceptionParam storagePutExceptionParam){
        return ResponseData.success(storagePutExceptionService.findListBySpec(storagePutExceptionParam));
    }
    
    /**
     * 入库复核
     * 审核 
     */
    @ResponseBody
    @RequestMapping("/confirm")
    public ResponseData confirm(StoragePutParam storagePutParam) {
		User user = userAop.getUser();
		ResponseData responseData = this.storagePutService.confirm(storagePutParam,user);
        if(responseData.getSuccess()){
        	this.checkComplete(storagePutParam.getStorageNumber());
        }
        return responseData;
    }
    
    /**
     * 入库复核
     * 单品审核 
     */
    @ResponseBody
    @RequestMapping("/shenhegoods")
    public ResponseData shenhegoods(StoragePutSingleParam storagePutSingleParam) {
		User user = userAop.getUser();
		ResponseData responseData = this.storagePutService.shenhegoods(storagePutSingleParam,user);
        if(responseData.getSuccess()){
        	this.checkComplete(storagePutSingleParam.getStorageNumber());
        }
        return responseData;
    }
    
    /**
     * 入库复核
     * 单品撤销
     */
    @ResponseBody
    @RequestMapping("/revokegoods")
    public ResponseData revokegoods(StoragePutSingleParam storagePutSingleParam) {
		User user = userAop.getUser();
        return this.storagePutService.revokegoods(storagePutSingleParam,user);
    }
    
    /**
     *  校验入库单是否完成
     */
    public void checkComplete(String storageNumber) {
    	StoragePutSingleParam storagePutSingleParam = new StoragePutSingleParam();
    	storagePutSingleParam.setStorageNumber(storageNumber);
    	StoragePutSingleResult spr = storagePutSingleService.findBySpecL1(storagePutSingleParam);//查询待审核和未入的明细
    	if (spr==null) {
    		//修改入库单为已完成
    		StoragePutParam spp = new StoragePutParam();
    		spp.setStorageNumber(storagePutSingleParam.getStorageNumber());
    		StoragePutResult sprt = storagePutService.findBySpec(spp);
    		spp.setId(sprt.getId());
    		spp.setBillstate("COMPLETED");
    		storagePutService.update(spp);
    		
            //更新入库订单  状态
            OrderPutParam opp = new OrderPutParam();
            opp.setPutNumber(sprt.getPutNumber());
            OrderPutResult opr = orderPutService.findBySpec(opp,null);
            opp.setId(opr.getId());
            opp.setBillstate("WAREHOUSED");
            opp.setCompleteTime(new Date());
            orderPutService.update(opp);
		} 
    }





	ResponseData storageLimitItems(User user, String positionNumber1, Long warehouseId, String goodsNo, String goodsNumber, String batchNumber) {
			//根据库位号查询库位信息
			//商品  占用存储位数
			AtomicInteger occupyStorageCount = new AtomicInteger();
			//商品  占用拣货位数
			AtomicInteger occupySelectCount = new AtomicInteger();

			//库位  存放商品类数
			AtomicInteger storageClassCount = new AtomicInteger();

			//根据库位判断是拣选位还是储位位
			//准备上架库位
//			String positionNumber1 = storagePutSingleParam.getPositionNumber();
			BasicPositionParam basicPositionParam1 = new BasicPositionParam();
			basicPositionParam1.setPositionNumber(positionNumber1);
			BasicPositionResult preparePosition = basicPositionService.findBySpec(basicPositionParam1,user.getDeptId(),user.getOperateId());
			String positionType = preparePosition.getPositionType();

			//准备上架的库位商品占用情况
			StorageStockParam storageOccupy = new StorageStockParam();
			storageOccupy.setDeptId(user.getDeptId());
			storageOccupy.setWarehouseId(warehouseId);
			storageOccupy.setPositionNumber(positionNumber1);
			storageOccupy.setGoodsNumber(goodsNumber);
			storageOccupy.setGoodsbatchs(goodsNo);
			storageOccupy.setGoodsbatchs(batchNumber);
			List<StorageStockResult> storageStockResults = storageStockService.finByOnlyOnePositionNumber1(storageOccupy);
			storageClassCount.set(storageStockResults.size());

			//该商品 目前库存所在库位
			StorageStockParam storageStockParam = new StorageStockParam();
			storageStockParam.setDeptId(user.getDeptId());
			storageStockParam.setDeliverId(user.getDeliverId());
			storageStockParam.setGoodsNumber(goodsNumber);
			storageStockParam.setGoodsNo(goodsNo);

			List<StorageStockResult> stockPageBySpec = this.storageStockService.findListBySpec1(storageStockParam, user.getOperateId());

			stockPageBySpec.stream().forEach(data -> {
				//库位号
				String positionNumber = data.getPositionNumber();
				//判断是拣选位还是储位位
				//根据库位号查询库位信息
				BasicPositionParam basicPositionParam2 = new BasicPositionParam();
				basicPositionParam2.setPositionNumber(positionNumber);
				BasicPositionResult basicPosition = basicPositionService.findBySpec(basicPositionParam2,user.getDeptId(),user.getOperateId());
				if(basicPosition.getPositionType().equals("拣货位")) {
					occupySelectCount.getAndIncrement();
				} else if(basicPosition.getPositionType().equals("储位位")) {
					occupyStorageCount.getAndIncrement();
				}
			});
			if(positionType.equals("拣货位") ){
				//一位3品
				if(storageClassCount.get() >= 3) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					return ResponseData.error("该库位为拣货位,已存储3类商品，无法入库！");
				}
				//一品3位
				if(occupySelectCount.get() >= 3) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					return ResponseData.error("该库位为拣货位,该商品已占用3个拣货位，无法入库！");
				}
			}
			if(positionType.equals("存储位")){
				//一位一品
				if(storageClassCount.get() >= 1) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					return ResponseData.error("该库位位存储位,已存储1类商品，无法入库！");
				}
				//一品多位
			}
			return ResponseData.success();
		}


}
